package eu.boss.fragments;

import java.io.IOException;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragment;

import eu.boss.R;
import eu.boss.activities.FragmentsSliderActivity;
import eu.boss.activities.NewPlayerActivity;
import eu.boss.activities.PlayerActivity;
import eu.boss.adapters.PlayerAdapter;
import eu.boss.model.Player;

/**
 * First fragment showing individual stats
 * @author Arnaud
 *
 */
public class StatsFragment extends SherlockFragment{
	private static int NEW_PLAYER_ID = 1;
	private static int SEE_STATS = 2;
	public static String FAILED = "FAILED";
	
	private ListView mLvPlayers;
	private ObjectMapper mMapper = new ObjectMapper();
	private int mPositionClicked;
	private FragmentsSliderActivity sliderActivity;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v= inflater.inflate(R.layout.stats,container, false);
		mLvPlayers = (ListView) v.findViewById(R.id.lvPlayers);
		sliderActivity = (FragmentsSliderActivity) getActivity();
		registerForContextMenu(mLvPlayers);
		try {
			initiateList();
		} catch (Exception e) {
			Log.e("JsonParseException", e.getMessage());
		} 
		return v;
	}

	
	/**
	 * Initialize the listview.
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public void initiateList() throws JsonParseException, JsonMappingException,
			IOException {
		//add a footer to "Add a new player"
		View footer = getActivity().getLayoutInflater().inflate(R.layout.footer, null);
		mLvPlayers.addFooterView(footer);
		updateList();

		// putting a onClickListener on every single listview item
		mLvPlayers.setOnItemClickListener(new OnItemClickListener() {
			/**
			 * @param position
			 *            : position of the item clicked
			 */
			public void onItemClick(AdapterView<?> a, View v, int position,
					long id) {
				mPositionClicked = position;				
				
				if(position < sliderActivity.getController().getStatsMessage().getPlayers().size()) {
					Player p = sliderActivity.getController().getStatsMessage().getPlayers().get(position);
					String s = null;
					try {
						// transforming a player in a json string
						s = mMapper.writeValueAsString(p);

					} catch (Exception e) {
						displayErrorMessage(e.toString());
					}
					Intent intent = new Intent(getActivity(),
							PlayerActivity.class);
					Bundle objetbunble = new Bundle();

					objetbunble.putString("player", s);

					intent.putExtras(objetbunble);
					startActivityForResult(intent, SEE_STATS);
				}

				else {
					// it means user clicked on the footer (to add a new player)
					Intent intent = new Intent(getActivity(),
							NewPlayerActivity.class);
					startActivityForResult(intent, NEW_PLAYER_ID);
				}
			}
		});
	}

	@Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        FragmentsSliderActivity fragmentActivity = (FragmentsSliderActivity) getActivity();
        menu.setHeaderTitle(fragmentActivity.getController().getStatsMessage().getPlayers().get(info.position).getName());
        menu.add(Menu.NONE, 0 , Menu.NONE, getString (R.string.init_stats));
        menu.add(Menu.NONE, 1, Menu.NONE, getString (R.string.delete));
    }

    @Override
    public boolean onContextItemSelected(final MenuItem item) {
    	final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
    	final FragmentsSliderActivity fragmentActivity = (FragmentsSliderActivity) getActivity();
    	
    	AlertDialog.Builder adb = new AlertDialog.Builder(
				getActivity());
		adb.setTitle(fragmentActivity.getController().getStatsMessage().getPlayers().get(info.position).getName());
		if (item.getItemId()==0)
			adb.setMessage(getString(R.string.are_you_sure_init));
		else
			adb.setMessage(getString(R.string.are_you_sure_delete));
		
		adb.setPositiveButton("Ok",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog,
							int which) {
						if (item.getItemId()==0)
				    		fragmentActivity.initPlayer(info.position);
				    	else    		  
				    		fragmentActivity.deletePlayer(info.position);

					}
				});
		adb.setNegativeButton("Annuler", null);
		adb.show();    	
    		  
        return super.onContextItemSelected(item);
    }
    

	/**
	 * Update list with the adapter
	 */
	public void updateList() {
		try
		{
			sliderActivity.getController().getStatsMessage().sortPlayerList();
			PlayerAdapter adapter = new PlayerAdapter(getActivity(), sliderActivity.getController().getStatsMessage().getPlayers());
			mLvPlayers.setAdapter(adapter);
		}
		catch (NullPointerException e)
		{
			Log.e("NullPointerException", "NullPointerException");
		}
	}
	

	/**
	 * Displaying error message in an AlertDialog
	 * @param msg message to display
	 */
	private void displayErrorMessage(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle(getString(R.string.error));
		builder.setMessage(msg);
		builder.setPositiveButton(R.string.ok, null);
		builder.show();
	}


	public int getPositionClicked() {
		return mPositionClicked;
	}
	
}
